package com.mason.forum.controller;

import com.mason.forum.common.APPResult;
import com.mason.forum.common.ResultCode;
import com.mason.forum.model.Article;
import com.mason.forum.model.User;
import com.mason.forum.model.vo.ArticleVO;
import com.mason.forum.service.IArticleService;
import com.mason.forum.utils.SessionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-10-06
 * Time: 19:39
 */
@Slf4j
@Api(tags = "帖子相关接口")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    /**
     * 发布新帖子
     * @param boardId 板块id
     * @param title 帖子标题
     * @param content 帖子正文
     * @return
     */
    @ApiOperation("发帖子")
    @PostMapping("/create")
    public APPResult publishArticle(HttpServletRequest request,
                                    @ApiParam("板块id") @RequestParam("boardId") @NonNull Long boardId,
                                    @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                                    @ApiParam("帖子正文") @RequestParam("content") @NonNull String content) {
        // 1. 用户是否禁言
        User user = SessionUtils.getUser(request);
        if(user.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());//已禁言
            return APPResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 2. 封装帖子对象
        Article article = new Article();
        article.setBoardId(boardId); //板块id
        article.setUserId(user.getId()); //作者id
        article.setTitle(title); //标题
        article.setContent(content); //正文
        // 3. 发布帖子
        articleService.create(article);//事务方法
        // 4. 发布成功
        return APPResult.success();
    }


    /**
     * 获取帖子列表
     * @param boardId 可有可无 1. 无代表所有帖子 2. 代表对应板块的帖子
     * @return 帖子列表
     */
    @ApiOperation("获取帖子列表")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    public APPResult<List<ArticleVO>> getAllByBoardId(
            @ApiParam("板块id") @RequestParam(value = "boardId", required = false) Long boardId) {
        List<ArticleVO> articles = null;
        if(boardId == null) {
            // 查询所有
            articles = articleService.selectAll();
        }else {
            // 查询板块下的所有
            articles = articleService.selectAllByBoardId(boardId);
        }
        //null则为空集合
        if(articles == null) {
            articles = new ArrayList<>();
        }
        //返回结果
        return APPResult.success(articles);
    }

    /**
     * 根据帖子id查询帖子详情
     * @param request 请求
     * @param id 帖子id
     * @return 帖子详情
     */
    @ApiOperation("根据帖子id查询帖子详情")
    @RequestMapping(value = "/detail", method = {RequestMethod.GET, RequestMethod.POST})
    public APPResult<ArticleVO> getDetail(HttpServletRequest request,
                                          @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {
        // 在controller层解决身份相关问题
        User user = SessionUtils.getUser(request);
        // service - 获取详情
        ArticleVO articleVO = articleService.selectDetailByAid(id);
        // 校验详情
        if(articleVO == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return APPResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 当前登录用户是否就是作者？
        if(user.getId().equals(articleVO.getUserId())) {
            articleVO.setOwn(true);
        }else {
            articleVO.setOwn(false);
        }
        // 成功返回
        return APPResult.success(articleVO);
    }

    @ApiOperation("编辑帖子信息")
    @PostMapping("/modify")
    public APPResult modify(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子正文") @RequestParam("content") @NonNull String content) {
        // 1. 判断是否有权限修改
        // 1.1 获取当前登录用户
        User user = SessionUtils.getUser(request);
        if(user.getState() == 1 || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return APPResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 1.2 获取当前文章的作者id
        Article article = articleService.selectById(id);
        if(article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return APPResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 1.3 判断
        if(article.getState() == 1 || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            return APPResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        if(!article.getUserId().equals(user.getId())) {
            log.warn(ResultCode.FAILED_UNAUTHORIZED.toString());
            return APPResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        // 2. service
        articleService.modify(id, title, content);
        // 3. 成功
        return APPResult.success();
    }

    @ApiOperation("给帖子点赞")
    @RequestMapping(value = "/like", method = {RequestMethod.GET, RequestMethod.POST})
    public APPResult thumpUp(HttpServletRequest request,
                             @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {
        // 当前用户如果无权则无法点赞
        User user = SessionUtils.getUser(request);
        if(user.getState() == 1 || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return APPResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // service - 点赞
        articleService.thumpUp(id);
        // 成功
        return APPResult.success();
    }

    /**
     * 删除帖子
     * @param request 请求
     * @param id 帖子id
     * @return
     */
    @ApiOperation("删除帖子")
    @RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
    public APPResult deleteById(HttpServletRequest request,
                                @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {
        // 1.查看当前用户信息
        User user = SessionUtils.getUser(request);
        if(user.getState() == 1 || user.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return APPResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 2.获取文章信息
        Article article = articleService.selectById(id);
        if(article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return APPResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(article.getState() == 1 || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            return APPResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        // 3. 判断用户是否有权删除
        if(!article.getUserId().equals(user.getId())) {
            log.warn(ResultCode.FAILED_UNAUTHORIZED.toString());
            return APPResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        // 4. service - 删除用户
        articleService.deleteById(article);
        // 5. 成功
        return APPResult.success();
    }

    @ApiOperation("获取用户的帖子列表")
    @RequestMapping(value = "/catalog", method = {RequestMethod.GET, RequestMethod.POST})
    public APPResult<List<ArticleVO>> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户ID") @RequestParam(value = "userId", required = false) Long userId) {

        // 如果UserId为空，则id为当前登录用户id
        User user = null;// 返回的user对象
        if(userId == null) {
            // 1. 如果id为null，从session中获取
            user = SessionUtils.getUser(request);
            if(user == null) {
                log.warn(ResultCode.FAILED_FORBIDDEN.toString());
                return APPResult.failed(ResultCode.FAILED_FORBIDDEN);//无权访问
            }
            userId = user.getId();
        }
        // service - 查询列表
        List<ArticleVO> articleVOS = articleService.selectAllByUserId(userId);
        // 查出来是null，转化为空集合
        if(articleVOS == null) {
            articleVOS = new ArrayList<>();
        }
        // 成功返回
        return APPResult.success(articleVOS);
    }



}
